package com.gjy.design.single;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过反射破坏单例
 *
 * @author gjy
 * @version 1.0
 * @since 2025-11-06 10:11:30
 */
public class SingletonBreakerByReflection {
    private static final Logger log = LoggerFactory.getLogger(SingletonBreakerByReflection.class);

    public static void main(String[] args) {
        try {
            // 1. 通过正常方式获取实例
            StaticInnerClassSingleton instance1 = StaticInnerClassSingleton.getInstance();
            log.info("正常获取的实例: {}", instance1.hashCode());

            // 2. 使用反射破坏单例
            Class<StaticInnerClassSingleton> clazz = StaticInnerClassSingleton.class;
            Constructor<StaticInnerClassSingleton> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true); // 暴力破解私有构造器

            // 3. 调用构造器创建新实例
            StaticInnerClassSingleton instance2 = constructor.newInstance();
            log.info("反射创建的实例: {}", instance2.hashCode());

            // 4. 比较两个实例，结果为 false，说明单例被破坏
            log.info("两个实例是否相同: {}", (instance1 == instance2));

        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                 InvocationTargetException e) {
            // 如果在单例的构造函数里加入了防御代码，会在这里抛出异常
            log.error("反射破坏失败，因为单例类中设置了防御措施！");
        }
    }

}
